package com.cloud.pole.common.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.cloud.pole.common.constant.CommonConstants;
import com.cloud.pole.common.context.BaseContextHandler;
import com.cloud.pole.common.exception.auth.UserTokenException;
import com.cloud.pole.common.util.jwt.IJWTInfo;
import com.cloud.pole.common.util.jwt.JWTInfo;
import com.cloud.pole.common.util.jwt.JwtTokenUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by ace on 2017/9/10.
 */
public class MerchantAuthRestInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(MerchantAuthRestInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        String token = request.getHeader(CommonConstants.AUTH_USER_TOKEN_HEADER);
        logger.info("MerchantAuthRestInterceptor::token[" + token + "] requestURI [" + request.getRequestURI() + "]");
        if(StringUtils.isEmpty(token)) {
            logger.error("token[" + token + "] requestURI [" + request.getRequestURI() + "] token is null!");
         	throw new UserTokenException("client token is null!");
        }
        IJWTInfo infoFromToken = JwtTokenUtil.getInfoFromToken(token);
        if(infoFromToken.getType() != JWTInfo.USER_TYPE_MERCHANTT){
           logger.error("token[" + token + "] requestURI [" + request.getRequestURI() + "] token is forbid!");
        	throw new UserTokenException("token is forbid!");
        }
        BaseContextHandler.setUsername(infoFromToken.getUniqueName());
        BaseContextHandler.setName(infoFromToken.getNickName());
        BaseContextHandler.setUserID(infoFromToken.getId());
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
